package server.handler.userHandler;

import com.alibaba.fastjson.JSONObject;
import common.EnvelopeMessage;
import common.bodies.LoginBody;
import common.bodies.UserBody;
import server.session.Session;
import server.dao.UserDao;
import server.handler.SimpleHandler;
import server.session.SessionManager;

public class LoginHandler implements SimpleHandler {
    @Override
    public void handle(EnvelopeMessage msg, Session session) {
        LoginBody body = JSONObject.toJavaObject((JSONObject) msg.getBody(), LoginBody.class);
        String username = body.getUsername();
        String password = body.getPassword();

        System.out.println(username + "尝试登录......");

        // 先检查用户是否已登录
        UserBody existingUser = new UserDao().selectUserByUsername(username);
        if (existingUser != null && SessionManager.getSession(existingUser.getId()) != null) {
            System.out.println("用户已登录，拒绝重复登录: " + username);
            sendLoginResponse(session, false, "该账号已在其他地方登录", null);
            return;
        }

        // 验证账号密码
        boolean isValid = new UserDao().selectUser(username, password);
        if (!isValid) {
            System.out.println("账号或密码错误: " + username);
            sendLoginResponse(session, false, "登录失败，请检查账号和密码", null);
            return;
        }

        // 登录成功处理
        UserBody user = new UserDao().selectUserByUsername(username);
        session.setClientId(user.getId());
        session.setClientName(user.getName());

        System.out.println("登录成功，绑定用户ID: " + user.getId());
        SessionManager.bind(user.getId(), session);

        sendLoginResponse(session, true, "登录成功，欢迎使用", user);
    }

    private void sendLoginResponse(Session session, boolean success, String message, UserBody user) {
        JSONObject response = new JSONObject();
        response.put("success", success);
        response.put("message", message);
        if (user != null) {
            response.put("user", user);
        }

        EnvelopeMessage back = new EnvelopeMessage("user", "login_result", response);
        String json = JSONObject.toJSONString(back);
        System.out.println("服务端返回: " + json);
        session.send(json);
    }
}